<template>
  <view class="order-form-container">
	  
		<uni-section title="订单名称" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderName" disabled placeholder="请输入任务名称" >
			</uni-easyinput>
		</uni-section>
	
		<uni-section title="工序类型" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderType"  disabled >
			</uni-easyinput>
		</uni-section>
		
		<uni-section title="审批人" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderType"   disabled >
			</uni-easyinput>
		</uni-section>
	 
		<uni-section title="剩余数量" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.number"  disabled >
			</uni-easyinput>
		</uni-section>
		
		<uni-section title="已完成数量" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.number"  :disabled="this.mode == 'edit'" placeholder="请输入已完成数量" >
			</uni-easyinput>
		</uni-section>
		
		<uni-section title="预估完成时间" type="line" padding>
			<uni-datetime-picker type="date" :clear-icon="false" v-model="form.planFinishTime"   :disabled="this.mode == 'edit'"/>
		</uni-section>


	<uni-section style="padding-bottom: 20rpx;">
		<view class="submit-btn-container">
			<button type="primary" size="mini" @click="submitForm">发起申请</button>
		</view>
	</uni-section>

  </view>
</template>

<script>
import request from '/utils/request.js';
import FileUpload from "/components/FileUpload.vue"
import { isEmpty } from "/utils/utils.js"

export default {

  data() {
    return {
			mode: 'add', // 当前模式：add（新增）、view（查看）、edit（编辑）
			isEditMode: false, // 是否处于编辑模式
			isDetailMode: false, // 是否处于详情模式（查看或编辑）
			selectedProcessIds: [],// 选中的工序ID数组
			selectedProcesses: [],// 回显的工序列表（包含完成天数）
      form: {
        orderName: '', // 任务名称
        orderType: '', // 任务类型
        orderPrice: '', // 任务价格
        number: '', // 总数量
				planFinishTime: '', // 计划完成时间
        orderAddress: '', // 收货地址
				orderStatus: '0', // 任务状态 0=草稿,1=未开始,2=已下发,3=已完成
        
        attachments: [], // 附件
				processes: [], // 工序列表
				isShowProcess: false,
      },
    }
  },
  onLoad(options) {
      // 根据路由参数判断页面模式
      if (options.orderId) {
        // 有id参数，进入详情模式
        this.mode = 'edit';
        this.isDetailMode = true;
        this.loadData(options.orderId);
				this.setPageTitle('任务详情');
      } else {
        // 无id参数，进入新增模式
        this.mode = 'add';
        this.isEditMode = true;
        this.setPageTitle('发起任务');
      }
    },
  methods: {
		// 设置页面标题
		setPageTitle(title) {
			uni.setNavigationBarTitle({
				title: title
			});
		},
    loadData(id) {
			request.get(`/system/initiate/${id}`).then(res => {
			  uni.hideLoading()
			  if (res.code === 200) {
					this.form.orderName = res.data.orderName
					this.form.orderType = res.data.orderType
					this.form.orderPrice = res.data.orderPrice
					this.form.number = res.data.number
					this.form.planFinishTime = res.data.planFinishTime
					this.form.orderAddress = res.data.orderAddress
					this.form.orderStatus = res.data.orderStatus
					this.form.attachments = []
					this.form.processes = []
			  } else {
			    uni.showToast({
			      title: res.msg,
			      icon: 'none'
			    })
			  }
			})
		},
		// 新增环节
		addProcess() {
			this.$refs.processModal.open();
		},
    
    onpopupopened(e) {
    	console.log('onpopupopened');
    },
    onpopupclosed(e) {
    	console.log('onpopupclosed');
    },
    
    // 选择附件
    chooseAttachment() {
      uni.chooseFile({
        count: 5, // 最多可选择文件数量
        success: (res) => {
          this.form.attachments = res.tempFiles;
        }
      })
    },
    
    // 移除附件
    removeAttachment(index) {
      this.form.attachments.splice(index, 1);
    },
    
    // 提交表单
    submitForm(type) {
			this.form.orderStatus = type
			
			//校验必填项
			if (isEmpty(this.form.orderName)) {
				uni.showToast({
					title: `请输入任务名称`,
					icon: 'error',
				})
				return
			}
			if (isEmpty(this.form.orderType)) {
				uni.showToast({
					title: `请选择任务类型`,
					icon: 'error',
				})
				return
			}
			
			if (isEmpty(this.form.number)) {
				uni.showToast({
					title: `请输入总数量`,
					iicon: 'error',
				})
				return
			}
			
      uni.showLoading({
        title: '提交中...',
      })

      let params = {
        type,
        ...this.form
      }

      request.post('/system/initiate', params).then(res => {
        uni.hideLoading()
        if (res.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          })
					// 跳转到任务列表页
					uni.switchTab({
						url: '/pages/workorder/orderList'
					});
					
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    },
		
		// 处理确认选择
		handleConfirmSelection(selectedItems) {
			// 根据选中的ID获取完整工序信息，并初始化完成天数
			this.selectedProcesses = [...selectedItems]

      console.log(this.selectedProcesses, '---111')
			// 更新选中ID数组
			this.selectedProcessIds =  this.selectedProcesses.filter(v => v.linkId !== -1);
			uni.showToast({
				title: `已选择 ${selectedItems.length} 个工序`,
				icon: 'success'
			});
		},
		
		// 处理弹窗关闭
		handleModalClose() {
			console.log('弹窗已关闭');
		},
		
		// 移除选中的工序
		removeProcess(index) {
			const process = this.selectedProcesses[index];
			this.selectedProcesses.splice(index, 1);
			
			// 更新选中ID数组
			this.selectedProcessIds =  this.selectedProcesses.filter(v => v.linkId !== process.linkId);
		},
		
		selectionChange(ids) {
			this.selectedProcessIds = ids
		},
		
		// 验证完成天数输入
		validateDays(process, event) {
			const value = event.mp.detail.value;
			
			// 限制为正整数
			if (value && (!/^\d+$/.test(value) || parseInt(value) <= 0)) {
				uni.showToast({
					title: '请输入正整数',
					icon: 'none'
				});
				process.days = null;
				return;
			}
			
			process.days = value ? parseInt(value) : null;
		}
	},
}
</script>

<style scoped lang="scss">
.order-form-container {
  padding: 20rpx;
}
.uni-form-item {
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
}
.uni-label {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}
.uni-input {
  padding: 15rpx;
  border: 1px solid #ccc;
  border-radius: 6rpx;
  font-size: 28rpx;
  min-height: 50rpx;
}
.attachment-list {
  margin-top: 10rpx;
}
.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1px solid #eee;
}
.close-icon {
  color: #999;
  font-size: 24rpx;
  padding: 5rpx;
  cursor: pointer;
}
.uni-button {
  margin-top: 20rpx;
}





/* 底部按钮 */
.modal-footer {
  display: flex;
  border-top: 1px solid #eee;
}
.cancel-btn, .confirm-btn {
  flex: 1;
  padding: 25rpx 0;
  text-align: center;
  font-size: 30rpx;
}
.cancel-btn {
  color: #333;
}
.confirm-btn {
  color: #007aff;
  font-weight: bold;
  border-left: 1px solid #eee;
}
.foot-sumbit {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 680rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  border-radius: 40rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 122, 255, 0.15);
  z-index: 999;
  
  /* 适配底部安全区 */
  /* padding-bottom: constant(safe-area-inset-bottom); */
  /* padding-bottom: env(safe-area-inset-bottom); */
}

/* 表单容器样式调整 */
.order-form-container {
  padding: 20rpx;
  padding-bottom: 220rpx; /* 增加底部内边距，避免内容被按钮遮挡 */
  
  /* 动态计算底部内边距（替代固定值，更灵活） */
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

/* 兼容非全面屏设备的备用方案 */
:root {
  --bottom-space: 160rpx;
}
.order-form-container {
  padding-bottom: var(--bottom-space);
}

/* 针对不同设备的动态调整（JS控制） */
@media screen and (min-device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  :root {
    --bottom-space: 180rpx; /* iPhone X系列等全面屏设备 */
  }
}
@media screen and (min-device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
  :root {
    --bottom-space: 200rpx; /* iPhone 12/13系列等全面屏设备 */
  }
}

/* 回显区域样式 */
.selected-processes {
  margin-top: 10rpx;
  .process-item {
    display: flex;
    align-items: center;
    padding: 6rpx 10rpx;
		margin-top: 6rpx;
    border: 2rpx solid #eee;
    
    text {
      flex: 1;
    }
    
    input {
      flex: 1;
      border: 1px solid #eee;
      border-radius: 4px;
      padding: 5px 10px;
      margin: 0 10px;
    }
  }
}

.submit-btn-container {
	display: flex;
	padding-bottom: 40rpx;
}
</style>
